package entity

import (
	"encoding/json"
	"kop/pb"
	"time"
)

type Captain struct {
	RoleID       int32 `gorm:"type:int;primary_key"`
	CaptainID    int32 `gorm:"type:int;primary_key"`
	Level        int32
	Exp          int32  // 技能经验
	Class        int32  // 船长爵位
	Skill2Level  int32  // 船长技能2
	Skill3Level  int32  // 船长技能3
	Talent       []byte `gorm:"type:jsonb" json:"-"` // 天赋 json
	BuildingID   int32
	RingUniqueID int32
	RingINT      int32  `gorm:"column:ring_int"` // 魔戒智力
	RingCOR      int32  `gorm:"column:ring_cor"` // 魔戒勇气
	RingCHR      int32  `gorm:"column:ring_chr"` // 魔戒魅力
	MaidID       int32  // 侍女ID
	Maid         []byte // 侍女属性
	//MaidINT       int32  `gorm:"column:maid_int"`                    // 侍女智力
	//MaidCOR       int32  `gorm:"column:maid_cor"`                    // 侍女勇气
	//MaidCHR       int32  `gorm:"column:maid_chr"`                    // 侍女魅力
	//MaidINTRate   int32  `gorm:"type:smallint;column:maid_int_rate"` // 侍女+智力比率
	//MaidCORRate   int32  `gorm:"type:smallint;column:maid_cor_rate"` // 侍女+勇气比率
	//MaidCHRRate   int32  `gorm:"type:smallint;column:maid_chr_rate"` // 侍女+魅力比率
	Ready bool // 上阵

	CreatedAt time.Time
	UpdatedAt time.Time
	TalentMap map[int32]int32 `sql:"-"`
	//PbMaidAttribute *pb.MaidAttribute `sql:"-"`
}

func (Captain) TableName() string {
	return "captains"
}

func (c *Captain) AfterFind() error {

	var talentMap = make(map[int32]int32, 0)
	_ = json.Unmarshal(c.Talent, &talentMap)

	//var maidAttribute = pb.MaidAttribute{
	//	Attribute:     &pb.Attribute{},
	//	AttributeRate: &pb.AttributeRate{},
	//}
	//_ = proto.Unmarshal(c.MaidAttribute, &maidAttribute)
	//
	//if maidAttribute.Attribute == nil {
	//	maidAttribute.Attribute = &pb.Attribute{}
	//}
	//if maidAttribute.AttributeRate == nil {
	//	maidAttribute.AttributeRate = &pb.AttributeRate{}
	//}

	c.TalentMap = talentMap
	//c.PbMaidAttribute = &maidAttribute
	return nil
}

func (c *Captain) BeforeCreate() error {
	c.Talent, _ = json.Marshal(c.TalentMap)
	//c.MaidAttribute, _ = proto.Marshal(c.PbMaidAttribute)
	return nil
}

func (c *Captain) BeforeSave() error {
	c.Talent, _ = json.Marshal(c.TalentMap)
	//c.MaidAttribute, _ = proto.Marshal(c.PbMaidAttribute)
	return nil
}

func (c *Captain) BeforeUpdate() error {
	c.Talent, _ = json.Marshal(c.TalentMap)
	//c.MaidAttribute, _ = proto.Marshal(c.PbMaidAttribute)
	return nil
}

func (c *Captain) RemoveRing() {

	c.RingUniqueID = 0
	c.RingINT = 0
	c.RingCOR = 0
	c.RingCHR = 0
}

func (c *Captain) EquipRing(ring *pb.Ring) {

	c.RingUniqueID = ring.ID
	c.RingINT = int32(float64(ring.Attribute.INT) / 10000 * float64(ring.UpValue+ring.UpValue2+10000))
	c.RingCOR = int32(float64(ring.Attribute.COR) / 10000 * float64(ring.UpValue+ring.UpValue2+10000))
	c.RingCHR = int32(float64(ring.Attribute.CHR) / 10000 * float64(ring.UpValue+ring.UpValue2+10000))
}
